<template>
  <div class="notification-center">
    <div class="notification-header">
      <h1 class="page-title">通知中心</h1>
      <div class="header-actions">
        <button class="refresh-btn" @click="refreshNotifications">
          🔄 刷新
        </button>
        <button
          class="mark-all-read-btn"
          @click="markAllAsRead"
          :disabled="unreadCount === 0"
        >
          📪 全部标记已读
        </button>
      </div>
    </div>

    <div class="notification-stats">
      <div class="stat-item">
        <span class="stat-label">总通知</span>
        <span class="stat-value">{{ notifications.length }}</span>
      </div>
      <div class="stat-item unread">
        <span class="stat-label">未读通知</span>
        <span class="stat-value">{{ unreadCount }}</span>
      </div>
    </div>

    <div class="notification-content">
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="notifications.length === 0" class="empty-state">
        <div class="empty-icon">📭</div>
        <h3>暂无通知</h3>
        <p>当有新的通知时，它们会显示在这里</p>
      </div>

      <div v-else class="notification-list">
        <!-- 修正：循环时正确读取嵌套字段 -->
        <div
          v-for="notification in notifications"
          :key="notification.noticeGiven.id"

          :class="['notification-card', { unread: notification.noticeGiven.isRead === 0 }]"
          @click="markAsRead(notification)"
        >
          <div class="card-header">
            <!-- 修正：标题从 noticeDetail 读取 -->
            <h3 class="notification-title">{{ notification.noticeDetail.title }}</h3>
            <!-- 修正：时间从 noticeGiven 读取 -->
            <span class="notification-time">{{ formatTime(notification.noticeGiven.sendTime) }}</span>
          </div>
          <div class="card-content">
            <!-- 修正：内容从 noticeDetail 读取 -->
            <p class="notification-message">{{ notification.noticeDetail.content }}</p>
          </div>
          <div class="card-footer">
            <!-- 修正：未读状态从 noticeGiven 读取 -->
            <span v-if="notification.noticeGiven.isRead === 0" class="unread-badge">未读</span>
            <span v-else class="read-badge">已读</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

// 添加组件存活状态标记
let isAlive = true;

// 修正：定义嵌套接口，与后端返回数据结构完全匹配
interface NoticeGiven {
  id: number;
  isRead: number;
  sendTime: string;
  oid: number | null;
  uid: number | null;
  nid: number;
  mid: number | null;
}

interface NoticeDetail {
  id: number;
  title: string;
  content: string;
  senderType: number;
  senderId: number;
  receiverType: number;
  receiverOneType: number | null;
  receiverId: number | null;
  createTime: string;
  isUsing: boolean;
}

interface Notification {
  noticeGiven: NoticeGiven;
  noticeDetail: NoticeDetail;
}

// 响应式数据
const notifications = ref<Notification[]>([]);
const unreadCount = ref(0);
const loading = ref(false);

// 修正：正确读取接口返回的 notices 字段
const fetchNotifications = async () => {
  try {
    loading.value = true;
    const token = localStorage.getItem('token');
    console.log('请求 token:', token);

    const response = await fetch('http://localhost:8080/ng/list', {
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    });

    console.log('接口状态码:', response.status);

    if (response.ok) {
      const result = await response.json();
      console.log('通知中心接口返回数据:', result);

      // 关键：检查组件是否仍然存活
      if (!isAlive) {
        console.log('组件已卸载，停止数据更新');
        return;
      }

      if (result.success) {
        notifications.value = result.notices || [];
        unreadCount.value = notifications.value.filter(
          item => item.noticeGiven.isRead === 0
        ).length;
        console.log('处理后的数据:', notifications.value);
        console.log('未读数量:', unreadCount.value);
      }
    } else {
      console.error('接口请求失败:', response.statusText);
    }
  } catch (error) {
    console.error('请求异常:', error);
  } finally {
    // 关键：检查组件是否仍然存活
    if (isAlive) {
      loading.value = false;
    }
  }
};

// 刷新通知
const refreshNotifications = (): void => {
  fetchNotifications();
};

// 修正：标记已读时传递 noticeGiven.id
const markAsRead = async (notification: Notification) => {
  if (notification.noticeGiven.isRead === 1) return;

  try {
    const token = localStorage.getItem('token');
    const response = await fetch(`http://localhost:8080/ng/markAsRead?id=${notification.noticeGiven.id}`, {
      method: 'PUT',
      headers: {
        'token': token || '',
        'Content-Type': 'application/json'
      }
    });

    if (response.ok) {
      const result = await response.json();
      if (result.success && isAlive) { // 关键：检查组件存活状态
        notification.noticeGiven.isRead = 1;
        unreadCount.value--;
      }
    }
  } catch (error) {
    console.error('标记已读失败:', error);
  }
};

// 修正：全部标记已读时处理嵌套字段
const markAllAsRead = async () => {
  try {
    const token = localStorage.getItem('token');
    const unreadNotifications = notifications.value.filter(
      item => item.noticeGiven.isRead === 0
    );

    for (const item of unreadNotifications) {
      await fetch(`http://localhost:8080/ng/markAsRead?id=${item.noticeGiven.id}`, {
        method: 'PUT',
        headers: {
          'token': token || '',
          'Content-Type': 'application/json'
        }
      });
    }

    // 关键：检查组件存活状态
    if (isAlive) {
      notifications.value.forEach(item => {
        item.noticeGiven.isRead = 1;
      });
      unreadCount.value = 0;
    }
  } catch (error) {
    console.error('全部标记已读失败:', error);
  }
};

// 时间格式化（保持不变）
const formatTime = (timeString: string) => {
  const date = new Date(timeString);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  if (diff < 60000) {
    return '刚刚';
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  } else if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 页面挂载时加载数据
onMounted(() => {
  console.log('通知中心页面挂载，开始加载数据');
  isAlive = true;
  fetchNotifications();
});

// 关键：组件卸载时标记为不存活
onUnmounted(() => {
  console.log('通知中心页面卸载');
  isAlive = false;
});
</script>

<style scoped>
/* 样式保持不变 */
.notification-center {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  color: #333;
  margin: 0;
  font-size: 1.8rem;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.refresh-btn, .mark-all-read-btn {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s ease;
}

.refresh-btn {
  background: #f8f9fa;
  color: #333;
  border: 1px solid #dee2e6;
}

.refresh-btn:hover {
  background: #e9ecef;
}

.mark-all-read-btn {
  background: #3498db;
  color: white;
}

.mark-all-read-btn:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-1px);
}

.mark-all-read-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.notification-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.stat-item {
  flex: 1;
  background: white;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.stat-item.unread {
  background: linear-gradient(135deg, #ffeaa7, #fab1a0);
}

.stat-label {
  display: block;
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  display: block;
  font-size: 2rem;
  font-weight: bold;
  color: #333;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
}

.spinner {
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.notification-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.notification-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border-left: 4px solid transparent;
}

.notification-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
}

.notification-card.unread {
  border-left-color: #3498db;
  background: #f8fafc;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.notification-title {
  margin: 0;
  color: #333;
  font-size: 1.1rem;
  flex: 1;
}

.notification-time {
  color: #999;
  font-size: 0.9rem;
  white-space: nowrap;
  margin-left: 15px;
}

.card-content {
  margin-bottom: 15px;
}

.notification-message {
  margin: 0;
  color: #666;
  line-height: 1.5;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

.unread-badge, .read-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.unread-badge {
  background: #e3f2fd;
  color: #1976d2;
}

.read-badge {
  background: #f5f5f5;
  color: #757575;
}

@media (max-width: 768px) {
  .notification-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
  }

  .notification-stats {
    flex-direction: column;
  }

  .card-header {
    flex-direction: column;
  }

  .notification-time {
    margin-left: 0;
    margin-top: 5px;
  }
}
</style>
